const { questionCategories } = require('../../utils/questions.js');
const StudyManager = require('../../utils/studyManager.js');

Page({
  data: {
    question: null,
    isFavorited: false,
    showAnswer: false
  },

  onLoad(options) {
    const { categoryId, topicId, questionId } = options;
    const category = questionCategories.find(c => c.id === categoryId);
    if (category) {
      const topic = category.topics.find(t => t.id === topicId);
      if (topic) {
        const question = topic.questions.find(q => q.id == questionId);
        this.setData({ 
          question,
          isFavorited: StudyManager.isFavorited(questionId)
        });
      }
    }
  },

  // 显示/隐藏答案
  toggleAnswer() {
    this.setData({
      showAnswer: !this.data.showAnswer
    });
  },

  // 收藏/取消收藏
  toggleFavorite() {
    const question = this.data.question;
    if (!question) return;

    if (this.data.isFavorited) {
      // 取消收藏
      StudyManager.removeFromFavorites(question.id);
      this.setData({ isFavorited: false });
      wx.showToast({
        title: '已取消收藏',
        icon: 'success'
      });
    } else {
      // 添加收藏
      const success = StudyManager.addToFavorites(
        question.id,
        question.categoryName || '未知分类',
        question.title,
        question.difficulty || 'medium'
      );
      
      if (success) {
        this.setData({ isFavorited: true });
        wx.showToast({
          title: '已添加到收藏',
          icon: 'success'
        });
      } else {
        wx.showToast({
          title: '已在收藏中',
          icon: 'none'
        });
      }
    }
  },

  // 开始练习这道题
  startPractice() {
    const question = this.data.question;
    if (question) {
      wx.navigateTo({
        url: `/pages/practice/practice?questionId=${question.id}`
      });
    }
  },

  // 分享功能
  onShareAppMessage() {
    const question = this.data.question;
    return {
      title: question ? `编程题目：${question.title}` : '编程题库',
      path: '/pages/index/index'
    };
  }
}); 